#!/usr/bin/python
# coding=utf-8

# useage:
# 使用前确保 ~/Desktop/emotion/e（p）目录有文件
# emotion.py -e ~/Desktop/emotion/e/  	#获得表情e目录下文件的json
# emotion.py -e ~/Desktop/emotion/p/		#获得表情p目录下文件的json
#

import sys
import os
import glob
import md5
import hashlib
import uuid
import json

"""


"fileMD5": "",
"fileName": "501.png",
"fileSize": 0,
"name": "",
"previewFileMD5": "",
"previewFileName": "501.png",
"previewFileSize": 0,
"resId": ""
"""


class SingleItem:
	def __init__(self, fileMD5, fileName, fileSize, name, previewFileMD5, previewFileName, previewFileSize, resId):
		self.fileMD5 = fileMD5
		self.fileName = fileName
		self.fileSize = fileSize
		self.name = name
		self.previewFileMD5 = previewFileMD5
		self.previewFileName = previewFileName
		self.previewFileSize = previewFileSize
		self.resId = resId


def CalcMD5(filepath):
	with open(filepath, 'rb') as f:
		md5obj = hashlib.md5()
		md5obj.update(f.read())
		hash = md5obj.hexdigest()
		return hash


def getUUID():
	# 获取 uuid
	# print(uuid.uuid1())
	return uuid.uuid1()


def DealSourceFile(_path, _file):
	print "\"fileName\": \"" + _file + "\","
	print "\"fileSize\": \"", os.path.getsize(str(_path) + _file), "\","
	_md5 = CalcMD5(_path + _file)
	print "\"fileMd5\": \"", _md5, "\","


def DealPreFile(_path, _file):
	print "\"previewFileName\": \"" + _file + "\","
	print "\"previewFileSize\": \"", os.path.getsize(str(_path) + _file), "\","
	md5 = CalcMD5(_path + _file)
	print "\"previewFileMD5\": \"", md5, "\","


def main(args):
	_path = args[1]
	_type = args[0]

	itemList = []

	if os.path.isdir(_path):
		files = os.listdir(_path)
		for file in files:
			"""
            "fileMD5": "",
            "fileName": "501.png",
            "fileSize": 0,
            "name": "",
            "previewFileMD5": "",
            "previewFileName": "501.png",
            "previewFileSize": 0,
            "resId": ""
            """

			fileMD5 = CalcMD5(_path + file)
			fileName = file
			fileSize = os.path.getsize(str(_path) + file)

			previewFileMD5 = CalcMD5(_path + file)
			previewFileName = file
			previewFileSize = os.path.getsize(str(_path) + file)
			resId = getUUID()

			item1 = SingleItem(fileMD5, fileName, fileSize, "", previewFileMD5, previewFileName, previewFileSize, resId)
			itemList.append(item1)
			if (_type == "-e"):
				DealSourceFile(_path, file)
			elif (_type == "-p"):
				DealPreFile(_path, file)
			else:
				print("please input emotion.py -e(-p) dir")

	json_str = json.dumps(itemList, default=lambda o: o.__dict__, sort_keys=True, indent=4)
	print (json_str)


if __name__ == "__main__":
	main(sys.argv[1:])
